Golang : Set or add headers for many or different handlers
Problem :
In Golang, setting headers can be done easily with the Set() method.
At the moment, you are setting headers for each individual handler in such as manner :
func handlerA(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler B."))
}
Instead of setting header for each individual handler manually, you want to use a function to set the headers.
NOTE : This method can apply to Add headers as well
Solution :
Create a common SetHeaders()
function that will write to http.ResponseWriter. For example :
func SetHeaders(w http.ResponseWriter) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
}
func handlerA(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler B."))
}
See also : Golang : How to Set or Add Header http.ResponseWriter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+28.8k Golang : Detect (OS) Operating System
+22.4k Golang : How to read JPG(JPEG), GIF and PNG files ?
+18.9k Golang : Read input from console line
+7.8k Golang : Example of how to detect which type of script a word belongs to
+17.6k Convert JSON to CSV in Golang
+48.6k Golang : Upload file from web browser to server
+9.8k Golang : Resumable upload to Google Drive(RESTful) example
+15.6k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+4.1k Javascript : Empty an array example
+31.1k Golang : Calculate percentage change of two values
+5.5k Golang : Display advertisement images or strings on random order
+13.7k Golang : Check if an integer is negative or positive